<template>
  <el-config-provider :locale="locale">
    <!-- 根据当前路由决定是否显示主布局 -->
    <div v-if="!isLoginPage" class="app-wrapper">
      <!-- 顶部导航 -->
      <el-header class="app-header">
        <div class="header-content">
          <div class="logo-container">
            <el-icon class="logo-icon"><Lock /></el-icon>
            <h1 class="logo-text">VulnGuard <span class="logo-subtext">AI 漏洞检测平台</span></h1>
          </div>
          <div class="header-actions">
            <MockDataToggle />
            <el-dropdown trigger="click" class="user-dropdown" @command="handleUserCommand">
              <span class="user-info">
                <el-avatar size="small" class="user-avatar">
                  <User />
                </el-avatar>
                <span class="user-name">{{ currentUser?.name || '管理员' }}</span>
                <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="el-icon-User" command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-Setting" command="settings">系统设置</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-Logout" command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-badge :value="unreadNotifications" class="notification-badge" :hidden="unreadNotifications === 0">
              <el-button type="text" class="notification-btn" @click="showNotifications">
                <Bell :size="20" />
              </el-button>
            </el-badge>
          </div>
        </div>
      </el-header>
      
      <div class="main-container">
        <!-- 侧边栏导航 -->
        <el-aside class="app-sidebar" :width="sidebarWidth" transition="el-zoom-in-left">
          <div class="sidebar-header" @click="toggleSidebar">
            <el-icon class="sidebar-toggle-icon"><Menu /></el-icon>
            <span v-show="!sidebarCollapsed" class="sidebar-title">主导航</span>
          </div>
          <el-menu 
              :default-openeds="['main']" 
              router 
              :collapse-transition="true"
              active-text-color="#409eff"
              background-color="#1f2937"
              text-color="#9ca3af"
              class="sidebar-menu"
              :collapse="sidebarCollapsed"
            >
              <el-sub-menu index="main">
                <template #title>
                  <el-icon><Home /></el-icon>
                  <span v-show="!sidebarCollapsed">仪表盘</span>
                </template>
                <el-menu-item index="/">
                  <el-icon><DataAnalysis /></el-icon>
                  <span v-show="!sidebarCollapsed">概览数据</span>
                </el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="scanning">
                <template #title>
                  <el-icon><Search /></el-icon>
                  <span v-show="!sidebarCollapsed">扫描管理</span>
                </template>
                <el-menu-item index="/scan">
                  <el-icon><Plus /></el-icon>
                  <span v-show="!sidebarCollapsed">新建扫描</span>
                </el-menu-item>
                <el-menu-item index="/scan/list">
                  <el-icon><View /></el-icon>
                  <span v-show="!sidebarCollapsed">扫描列表</span>
                </el-menu-item>
                <el-menu-item index="/scan/history">
                  <el-icon><Clock /></el-icon>
                  <span v-show="!sidebarCollapsed">扫描历史</span>
                </el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="vulnerabilities">
                <template #title>
                  <el-icon><Warning /></el-icon>
                  <span v-show="!sidebarCollapsed">漏洞管理</span>
                </template>
                <el-menu-item index="/results">
                  <el-icon><View /></el-icon>
                  <span v-show="!sidebarCollapsed">漏洞列表</span>
                </el-menu-item>
                <el-menu-item index="/attack-path">
                  <el-icon><Link /></el-icon>
                  <span v-show="!sidebarCollapsed">攻击路径</span>
                </el-menu-item>
                <el-menu-item index="/suggestions">
                  <el-icon><Tools /></el-icon>
                  <span v-show="!sidebarCollapsed">修复建议</span>
                </el-menu-item>
              </el-sub-menu>
              
              <el-menu-item index="/target-range">
                <template #title>
                  <el-icon><Location /></el-icon>
                  <span v-show="!sidebarCollapsed">靶场系统</span>
                </template>
              </el-menu-item>
              
              <el-sub-menu index="security">
                <template #title>
                  <el-icon><Lock /></el-icon>
                  <span v-show="!sidebarCollapsed">安全管理</span>
                </template>
                <el-menu-item index="/security/dashboard">
                  <el-icon><DataAnalysis /></el-icon>
                  <span v-show="!sidebarCollapsed">安全概览</span>
                </el-menu-item>
                <el-menu-item index="/security/compliance">
                  <el-icon><Document /></el-icon>
                  <span v-show="!sidebarCollapsed">合规管理</span>
                </el-menu-item>
                <el-menu-item index="/security/knowledge-base">
                  <el-icon><Document /></el-icon>
                  <span v-show="!sidebarCollapsed">知识库</span>
                </el-menu-item>
                <el-menu-item index="/security/incident-response">
                  <el-icon><Warning /></el-icon>
                  <span v-show="!sidebarCollapsed">事件响应</span>
                </el-menu-item>
                <el-menu-item index="/security/report">
                  <el-icon><Document /></el-icon>
                  <span v-show="!sidebarCollapsed">报告生成</span>
                </el-menu-item>
                <el-menu-item index="/security/baseline">
                  <el-icon><Aim /></el-icon>
                  <span v-show="!sidebarCollapsed">基线配置</span>
                </el-menu-item>
                <el-menu-item index="/security/vulnerability">
                  <el-icon><Search /></el-icon>
                  <span v-show="!sidebarCollapsed">漏洞管理</span>
                </el-menu-item>
                <el-menu-item index="/security/user-management">
                  <el-icon><User /></el-icon>
                  <span v-show="!sidebarCollapsed">用户管理</span>
                </el-menu-item>
              </el-sub-menu>
              
              <el-menu-item index="/settings">
                <template #title>
                  <el-icon><SettingIcon /></el-icon>
                  <span v-show="!sidebarCollapsed">系统设置</span>
                </template>
              </el-menu-item>
            </el-menu>
        </el-aside>
        
        <!-- 主内容区域 -->
        <el-main class="app-content">
          <div class="content-wrapper">
            <transition name="fade-transform" mode="out-in">
              <router-view v-key="$route.fullPath" />
            </transition>
          </div>
          
          <!-- 系统通知组件 -->
          <Teleport to="body">
            <NotificationDrawer :visible="notificationVisible" @update:visible="notificationVisible = $event" @close="notificationVisible = false" />
          </Teleport>
        </el-main>
      </div>
      
      <!-- 加载遮罩层 -->
      <div v-if="isGlobalLoading" class="global-loading">
        <el-loading-spinner size="large" />
        <p class="loading-text">{{ loadingText }}</p>
      </div>
    </div>
    
    <!-- 登录页面直接显示内容，不包含任何导航元素 -->
    <div v-else>
      <transition name="fade-transform" mode="out-in">
        <router-view v-key="$route.fullPath" />
      </transition>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import { 
  User, Bell, ArrowDown, Menu, 
  Search, Document, Warning, 
  Clock, Plus, View, Link, Location,
  HomeFilled as Home,      // 用HomeFilled替代Home
  Lock as Shield,          // 用Lock替代Shield
  Setting as SettingIcon,  // 重命名Setting
  Refresh as TrendCharts,  // 用Refresh替代TrendCharts
  Document as DataAnalysis, // 用Document替代DataAnalysis
  Operation as Tools,      // 用Operation替代Tools
  Aim                      // 新增Aim图标
} from '@element-plus/icons-vue'
import apiService from './services/apiService.js'
import NotificationDrawer from './components/NotificationDrawer.vue'
import MockDataToggle from './components/MockDataToggle.vue'

const router = useRouter()
const currentUser = ref(null)
const sidebarCollapsed = ref(false)
const sidebarWidth = computed(() => sidebarCollapsed.value ? '64px' : '240px')
const unreadNotifications = ref(0)
const notificationVisible = ref(false)
const isGlobalLoading = ref(false)
const loadingText = ref('加载中...')

// 用户命令处理
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        isGlobalLoading.value = true
        loadingText.value = '正在退出登录...'
        await apiService.logout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        ElMessage.error('退出登录失败')
      } finally {
        isGlobalLoading.value = false
      }
      break
    default:
      break
  }
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 显示通知
const showNotifications = () => {
  notificationVisible.value = true
  unreadNotifications.value = 0
}

// 监听数据模式变化事件
const setupDataModeListener = () => {
  try {
    const handleDataSourceChange = () => {
      ElNotification.success({
        title: '数据模式已更新',
        message: `当前使用${apiService?.useMockData?.value ? '模拟' : '真实'}数据`,
        duration: 3000
      })
    }
    
    window.addEventListener('data-source-changed', handleDataSourceChange)
    
    // 清理函数
    return () => {
      window.removeEventListener('data-source-changed', handleDataSourceChange)
    }
  } catch (error) {
    console.error('设置数据模式监听器失败:', error)
    return () => {}
  }
}

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    currentUser.value = await apiService.getCurrentUser()
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 组件挂载时执行
onMounted(() => {
  try {
    fetchCurrentUser()
    const cleanup = setupDataModeListener()
    
    // 组件卸载时清理
    // 在实际使用中应在onUnmounted钩子中调用cleanup
  } catch (error) {
    console.error('组件挂载初始化失败:', error)
  }
})

// 判断是否为登录页面
const isLoginPage = computed(() => {
  return router.currentRoute.value.path === '/login'
})

// 使用中文语言包
const locale = zhCn

// 设置全局加载
const setGlobalLoading = (loading, text = '加载中...') => {
  isGlobalLoading.value = loading
  loadingText.value = text
}
</script>

<style scoped>
/* 全局样式 */
.app-wrapper {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 顶部导航样式 */
.app-header {
  background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
  color: #ffffff;
  padding: 0 24px;
  height: 64px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 24px;
  color: #409eff;
}

.logo-text {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.logo-subtext {
  font-size: 12px;
  font-weight: normal;
  color: #9ca3af;
  margin-left: 4px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 模拟数据切换按钮样式调整 */
.header-actions :deep(.mock-data-toggle) {
  margin-right: 8px;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-avatar {
  background-color: #409eff;
}

.user-name {
  font-size: 14px;
}

.dropdown-icon {
  font-size: 12px;
}

.notification-badge {
  transition: transform 0.2s;
}

.notification-badge:hover {
  transform: scale(1.1);
}

.notification-btn {
  color: #ffffff;
  transition: color 0.2s;
}

.notification-btn:hover {
  color: #409eff;
}

/* 主容器样式 */
.main-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 64px);
}

/* 侧边栏样式 */
.app-sidebar {
  background-color: #1f2937;
  border-right: 1px solid #374151;
  transition: all 0.3s ease;
  overflow: hidden;
}

.sidebar-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  border-bottom: 1px solid #374151;
  cursor: pointer;
  transition: background-color 0.2s;
}

.sidebar-header:hover {
  background-color: #374151;
}

.sidebar-toggle-icon {
  color: #9ca3af;
}

.sidebar-title {
  color: #f3f4f6;
  font-size: 14px;
  font-weight: 500;
}

.sidebar-menu {
  border-right: none;
  height: calc(100% - 56px);
  overflow-y: auto;
}

.sidebar-menu .el-menu-item,
.sidebar-menu .el-sub-menu__title {
  height: 48px;
  line-height: 48px;
  color: #9ca3af;
  transition: all 0.2s;
}

.sidebar-menu .el-menu-item:hover,
.sidebar-menu .el-sub-menu__title:hover {
  background-color: #374151;
  color: #f3f4f6;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #409eff;
  color: #ffffff;
}

.sidebar-menu .el-icon {
  color: inherit;
}

/* 主内容区域样式 */
.app-content {
  flex: 1;
  padding: 0;
  overflow-y: auto;
  background-color: #f5f7fa;
  background-image: radial-gradient(#e2e8f0 1px, transparent 1px);
  background-size: 20px 20px;
}

/* 内容包装器 - 精美样式 */
.content-wrapper {
  padding: 24px;
  max-width: 1600px;
  margin: 0 auto;
  width: 100%;
  min-height: calc(100vh - 64px);
  position: relative;
}

/* 为内容区域添加柔和的阴影边框 */
.content-wrapper::before {
  content: '';
  position: absolute;
  top: 8px;
  left: 8px;
  right: 8px;
  bottom: 8px;
  background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 50%);
  border-radius: 8px;
  pointer-events: none;
  z-index: 1;
}

/* 全局加载样式 */
.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  animation: fadeIn 0.3s ease;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
  color: #606266;
}

/* 过渡动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-transform-enter-from,
.fade-transform-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>